<?php 

require_once './_common.inc';

function rsa_encrypt($numstring, $e, $n){
	
	if(strlen($numstring) > $n)
		echo "<b><i>WARNING: Input greater than modulo.</b></i>";

	$ct = bcpowmod($numstring, $e, $n);
	return $ct;
	
};


function rsa_decrypt($ct, $d, $n){

	if(strlen($ct) > $n)
		echo "<b><i>WARNING: Input greater than modulo.</b></i>";

	$numstring = bcpowmod($ct, $d, $n);
	return $numstring;
	
};

function rsa_encrypt_text($string, $e, $n){
	
	if(strlen($string) > 48){
		
		$strset = split_ascii($string);
		
		for($i = 0; $i < sizeof($strset); $i++){
			$numstring = ascii_to_num($strset[$i]);
			$ct[$i] = rsa_encrypt($numstring, $e, $n);
		}
	
	return $ct;
		
	}else{
		$numstring = ascii_to_num($string);
		$ct[0] = rsa_encrypt($numstring, $e, $n);
		return $ct;
	}
};

function rsa_decrypt_text($ct_array, $d, $n){
	
	for($j = 0; $j < sizeof($ct_array); $j++){
	
		$numstring = bcpowmod($ct_array[$j], $d, $n);
		$m[$j] = num_to_ascii($numstring);
	}
	return implode($m);
};

function rsa_sign($m, $d, $n){
	
	$h = md5($m);
	
	$decvalues = array('0' => '0', '1' => '1', '2' => '2',
               '3' => '3', '4' => '4', '5' => '5',
               '6' => '6', '7' => '7', '8' => '8',
               '9' => '9', 'a' => '10', 'b' => '11',
               'c' => '12', 'd' => '13', 'e' => '14',
               'f' => '15');
    
	$dec = '0';
    $hrev = strrev($h);
    
    for($i = 0; $i < strlen($hrev); $i++)
    	$dec = bcadd(bcmul(bcpow('16',$i), $decvalues[$hrev[$i]]), $dec);
    
    $signature = bcpowmod($dec, $d, $n);
	
	return $signature;
}


function rsa_check_signature($s, $e, $n){

	$h_int = bcpowmod($s, $e, $n);

	$hexvalues = array('0','1','2','3','4','5','6','7',
               '8','9','a','b','c','d','e','f');
	
	$h = '';
     while($h_int != '0')
     {
        $h = $hexvalues[bcmod($h_int,'16')] . $h;
        $h_int = bcdiv($h_int,'16',0);
    }
    
	return $h;
};

function generate_keys($bitDepth = 1024){
	$cmd = "java -jar rsa_keygen.jar " . $bitDepth;
	
	$output = shell_exec($cmd);
	
	//$output = preg_replace('/\s/', '', $output);
	
	$outputArray = preg_split('/[\r\n]+/', $output, -1, PREG_SPLIT_NO_EMPTY);
	
	for($i = 0; $i < count($outputArray); $i++){
		$outputArray[$i] = preg_replace('/\s+/', '', $outputArray[$i]);
		$t = preg_split('/:+/', $outputArray[$i], -1);
		$key[$t[0]] = $t[1]; 
	}
	
	// Uncomment to print all key data
	/*
	 echo "<PRE>";
	 print_r($key);
	 echo "</PRE>";
	 */

	return($key);
}


?>